<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo  in    cartInfoList" :key="cartInfo.skuId">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!!cartInfo.isChecked"
              @change="changeOnecheecked(cartInfo)">
          </li>
          <li class="cart-list-con2">
            <img :src=cartInfo.imgUrl>
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeSkuNum('descrement', cartInfo)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)">
            <a href="javascript:void(0)" class="plus" @click="changeSkuNum('increment', cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuNum * cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet" @click="showDialogByDelOneCartInfo(cartInfo)">删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>




      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="showDialogByDelSelected">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span> {{ selectCount }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade" >结算</router-link>
        </div>
      </div>
    </div>
    <Dialog :visible.sync="visible">

      <template v-slot:header>
        <div>
          <h3>提示</h3>
        </div>
      </template>

      <template>
        <p>你真的要删除{{ isDelteOne ? '这条' : '所选中的' }}</p>
      </template>
      <template v-slot:footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn btn-primary" @click="delCartInfo">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import { reqDeleteSelectedCartInfo, reqAddOrUpdateSkuInfoToShopCart, reqShopCartListData, reqChangeShopCartInfoState, reqDeleteOneCartInfo, reqChangeAllCartState } from "@/api"
import { skuNumReg } from '@/utils/reg';

export default {
  name: 'ShopCart',
  data() {
    return {
      cartInfoList: [],
      visible: false,//控制对话框的显示与隐藏

      isDelteOne: false,//是否删除一条数据
      skuId: 0,
      leftCartInfoList: [],//剩余的数组,
      timerId:0,//定时器
      num,//发往服务器的差值
    }
  },
  mounted() {
    this.getShopCartList()
  },
  watch: {
    visible: {
      immediate: true,
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = true
        } else {
          document.documentElement.style.overflow = false;
        }
      }
    }
  },
  methods: {
    //获取购物车中的数据
    async getShopCartList() {
      const res = await reqShopCartListData();
      console.log(res)
      if (res.code == 200) {
        this.cartInfoList = res.data[0].cartInfoList
        this.$message.success("获取数据成功")
      }
    },
    //单选
    async changeOnecheecked(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;

      const res = await reqChangeShopCartInfoState(cartInfo.skuId, isChecked);
      cartInfo.isChecked = isChecked;
    },
    //点击删除一条数据时弹出对话框
    showDialogByDelOneCartInfo(cartInfo) {

      if (!cartInfo.isChecked) return
      this.skuId = cartInfo.skuId;
      this.isDelteOne = true;
      this.visible = true;

    },
    //点击确定按钮看删除的是一条数据还是多条数据
    async delCartInfo() {
      //判断是删除一条数据，还是多条数据
      if (this.isDelteOne) {

        const res = await reqDeleteOneCartInfo(this.skuId)

        if (res.code == 200) {
          //隐藏对话框
          this.visible = false
          //重新渲染剩余的数据
          this.cartInfoList = this.cartInfoList.
            filter(item => item.skuId != this.skuId)
            this.$message.success('操作成功')
        }

        return
      } else {
        const res = await reqDeleteSelectedCartInfo(this.skuIdList)
        if (res.code == 200) {
          //关闭兑换框
          this.visible = false;
          //使用剩余的数组来渲染数据
          this.cartInfoList = this.leftCartInfoList;
          this.$message.success('操作成功')

        }
      }
    },
    //点击批量删除数据
    showDialogByDelSelected() {
      //每次弹出对话框的时候都要去清空原来的数组
      this.skuIdList = [];
      this.leftCartInfoList = [];
      //显示兑换框
      this.visible = true;
      //判断是否是一条
      this.isDelteOne = false;
      //收集待删除数组的id
      this.cartInfoList.forEach(item => {
        if (item.isChecked) {
          this.skuIdList.push(item.skuId)
          this.$message.success('数据已更新')
        } else {
          //将未删除的数据存储到未删除的数组
          this.leftCartInfoList.push(item);
        }
      })
    },
    //改变购物车商品的数量
    changeSkuNum(type, cartInfo, event) {
      //给一个初始值，用于计算插值
      // let num = 0;
      switch (type) {
        case 'descrement':
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--;
            this.num--;
          }
          break;

        case 'increment':
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
           this.num++;
          }
          break;
        case 'change':
          //直接从输入框修改数量的时候
          let newValue = event.target.value;
        
          let oldValue = cartInfo.skuNum;


          if (skuNumReg.test(newValue)) {
        
            //是数字
            cartInfo.skuNum = event.target.value
           this.num = cartInfo.skuNum - oldValue;
            if (cartInfo.skuNum > 200) {
              cartInfo.skuNum = 200;
              this.num = 200 - oldValue;
            } 
          }else {
              event.target.value = oldValue;
              // num = 0;
            }
          break
      }
      if(this.num=0) return //就不要发送请求了
      if(this.timerId) clearTimeout(this.timerId);
this.timerId=setTimeout(async() => {
  const res=  await reqAddOrUpdateSkuInfoToShopCart(cartInfo.skuId, num);
if(res.code==200){
  this.$message.success('数据更新成功')
}else{
  this.$message.error('数据更新失败')
}
this.num=0;//清楚以前的数据
}, 500);


      //最后发送数据渲染页面
    




    }
  },
  computed: {
    //全选与全不选
    checkAll: {
      get() {
        //读取每个输入框的数据
        this.cartInfoList.every(item => {
          item.isChecked == 1

        })
      },

      async set(val) {
        console.log(val)
        let isChecked = val ? 1 : 0;
        const skuIdList = [];
        this.cartInfoList.forEach(item => {

          item.isChecked = isChecked;
          skuIdList.push(item.skuId)
          //然后发送请求

        })


        const res = await reqChangeAllCartState(

          isChecked,
          skuIdList

        );
        if (res.code == 200) {
          alert("批量更新成功")
        }

      }





    },
    //统计选中商品的shuliang
    selectCount() {
      //根据选中为选中确定商品的数量
      return this.cartInfoList.reduce((pre, item) => pre + item.isChecked, 0)
    },
    //统计总价
    selectMoney() {
      return this.cartInfoList.reduce((pre, item) => pre + item.isChecked * item.skuNum * item.skuPrice, 0)
    }

  }
}

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      &>div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        &>li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }


      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>